/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_cyclonedds/listener_impl/TopicListenerImpl.hpp"
#include "dal_cyclonedds/entity_impl/DalTopicImpl.hpp"
#include "dal_cyclonedds/utils/log.hpp"

static void on_inconsistent_topic(dds_entity_t topic, 
    const dds_inconsistent_topic_status_t status, void* arg)
{
    dal_topic_listener_callbacks_t *callbacks_ 
        = reinterpret_cast<dal_topic_listener_callbacks_t*>(arg);
    if (callbacks_->on_inconsistent_topic == nullptr)
        return;

    dal_topic_t dal_topic;
    dal_inconsistent_topic_status_t dal_status;

    DalTopicImpl* topic_impl = new DalTopicImpl(topic, nullptr);
    if (!topic_impl) {
        LOG_ERROR() << "DalTopicImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_topic.handle_ = topic_impl;
    StatusConverter::GetInstance()->ConvertInconsistentTopicStatusFromCycloneddsToDal(&status,
                                                                                    &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_inconsistent_topic)(&dal_topic, &dal_status, data);
    delete topic_impl;
}

TopicListenerImpl::TopicListenerImpl(dal_topic_listener_callbacks_t callbacks)
    : callbacks_(callbacks) {}

TopicListenerImpl::~TopicListenerImpl()
{
    // c_listener release while participant is releasing.
}

dds_listener_t* TopicListenerImpl::CycloneDDSListener()
{
    if (c_listener_ == nullptr) {
        try {
            c_listener_ = dds_create_listener(NULL);
        }
        catch(...) {
            std::cout << "bug" << '\n';
        }
    }
    dds_lset_inconsistent_topic_arg(c_listener_, on_inconsistent_topic, &callbacks_, true);
    return c_listener_;
}